<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2017/4/16
 * Time: 14:34
 */

namespace app\home\controller\user;


class Ask extends Common
{
    private $mod;
    protected $beforeActionList = [
        'beforeAdd' => ['only'=>'add']
    ];
    public function _initialize()
    {
        parent::_initialize();
        $this->mod = model('ask');
        $this->_name = 'Ask';
        $cate = cache('askCate');
        $this->assign('askCate',$cate['cate']);
        $this->assign('askCateTree',$cate['tree']);
    }
    public function index(){
        $where['user_id'] = $this->userInfo['id'];
        $lists = $this->mod->where($where)->order('id desc')->paginate(10);

        $this->assign('lists',$lists);
        $this->assign('pages',$lists->render());
        return $this->fetch();
    }
    public function help(){
        $where['answer_user_id'] = $this->userInfo['id'];
        $lists = $this->mod->where($where)->order('id desc')->paginate(10);
        $this->assign('lists',$lists);
        $this->assign('pages',$lists->render());
        return $this->fetch();
    }
    public function answer(){
        $id = input('param.id/d',0);
        $where['id'] = $id;
        $where['answer_user_id'] = $this->userInfo['id'];
        $info = $this->mod->where($where)->find();
        $answer = model('answer')->where(['ask_id'=>$id,'user_id'=>$this->userInfo['id']])->select();
        $this->assign('info',$info);
        $this->assign('answer',$answer);
        return $this->fetch();
    }
    public function myanswer(){
        $answer = model('answer')->where(['user_id'=>$this->userInfo['id']])->paginate();
        $this->assign('lists',$answer);
        $this->assign('pages',$answer->render());
        return $this->fetch();
    }
    public function answerDo(){
        $this->_name = 'Answer';
        \app\common\model\Answer::event('before_insert',function($obj){
            $obj->user_id = $this->userInfo['id'];
            $obj->user_name = $this->userInfo['nickname'];
            $obj->status  = $this->site['checkanswer'] == 0 ?1 : 0;
        });
        \app\common\model\Answer::event('after_insert',function($obj){
            model('ask')->save(['answer'=>1],['id'=>$obj->ask_id]);
        });
        parent::addDo();
    }
    public function beforeAdd(){

    }
    public function detail(){
        $id = input('param.id/d',0);
        if($id){
            $ask = model('ask')->where(['id'=>$id])->find();
            $answer = model('answer')->where(['ask_id'=>$id])->select();
            $this->assign('info',$ask);
            $this->assign('answer',$answer);
        }else{
            $this->error('参数错误');
        }
        return $this->fetch();
    }
    public function addDo(){
        \app\common\model\Ask::event('before_insert',function($obj){
            $obj->user_id = $this->userInfo['id'];
            $obj->status  = $this->site['checkask'] == 0 ?1 : 0;
        });
        parent::addDo();
    }
}